
/*
 * This file contains function to find students and hold on to them in an array
 */


// Globals for students
var allStudents = new Array(); // array with students 
var numbOfCourse = 0; // number of courses


/*
 * this function will find all courses for one semster and for the right department
 * and run a function to get students for all course
 */
function listAllStudents (sem, dep) {  
    semester = sem; // set the semester
    department = dep;  // set the department
    done = false; // set the buffer loader flag
    $.ajax ({
        url : 'https://tvil.hig.no/json_services/getDepartmentCourseList.php',
        crossDomain : true,
        data : {
            'department' : department, // send values in post
            'period' : semester
        },
        type : 'POST',
        dataType : 'json',
        success : function (data) {
            numbOfCourse = data.length+1;  // sets the numberofcourses
            for (x=0; x<data.length; x++) { // loops trought the courses
                findStudents(data[x].id, x); // find students in that course and what number the course is
            }    
            findStudents("390", data.length); // for bachelor IMT vår 2012
            waitForStudents(1); // starts the buffer loader
        }        
    });   
}

function findStudents (course, length) {
    var course_id = course; // sets the course id
    $.ajax ({
        url : 'https://tvil.hig.no/json_services/getCourseStudentList.php',
        crossDomain : true,
        data : {
            'course_id' : course_id
        },
        type : 'POST',
        dataType : 'json',
        success : function (data) {                      
            for (y in data) {   // loops trought the students
                if(checkForName(data[y].uid) && data[y].uid.substring(0, 2) < 10){ // if not in array and studnr not starts with 10                    
                    var student = new studentClass(data[y].uid, data[y].givenname, data[y].surename); // create an student object
                    allStudents.push(student); // add object to array
                }
            }
            if(length == numbOfCourse-1) { // if end of course
                done = true; // stop the buffer loader
                sortArray(); // sort the array
                displayStudents(); // displays the student    
            }
        }
    });
}

/*
 * This function sorts the array with students
 */
function sortArray() {
    var array = new Array();    // create a temp array
    var onBottom = true;    // sets on bottom flag
    array.push(allStudents[0]); // add one student to temp array to have something to check against
    for(s=1; s<allStudents.length; s++) { // loop trough the student array
        for(i=0; i<array.length; i++) { // loop trough temp array
            if(allStudents[s].get_name().toLowerCase() > array[i].get_name().toLowerCase()){                
                array.splice(i,0,allStudents[s]); // checks if the object from student array
                onBottom = false;                // is gona be put before the temp array object
                break;                          // then add to temp array and set on bottom to false
            }
        }        
        if(onBottom == true) {      // if the object belong to the bottom then add to bottom to temp array
            array.push(allStudents[s]);
        }        
    }        
    array.reverse(); // gjør dette fordi if setningen ikke fungerer som den skal når vi snur større enn tegnet, hvorfor?
    allStudents = array;    // sets the student array = temp array
}


/*
 * this function checks if the student is already in the student array
 */
function checkForName(uid){
    if(uid == $(document).data ('uid')){ // if uid = user ID dont add to array
        return false;
    }
    for (i in allStudents){
        if(uid == allStudents[i].get_uId()){ // if studentnr already exist dont add
            return false;
        }
    }    
    return true;
}


/*
 * this function returns an array with student info
 */
function getUser(uid, returnData) { // callback function
    $.ajax ({
        url : 'https://tvil.hig.no/json_services/getUserDetails.php',
        data : {
            'uid': uid
        },
        crossDomain : true,
        type : 'POST',
        dataType : 'json',
        success : function (data) {
            var array = new Array(); // creates a temp array
            array.push(uid);    // add userid to the array
            for (e in data) {
                array.push(data[e]); // puts userinfo in an array
            }                             
            returnData(array); // returns array with callback
        }
    });
}


/*
 * this function looks up a student on studentnumber or name
 */
function searchStudent() {    
    var search = document.getElementById('students').firstChild.value; // gets the search value
    var isNumber = /^\d+$/.test(search) // kode fra http://stackoverflow.com/questions/1779013/check-if-string-contains-only-digits
    var temp = document.getElementById('students').firstChild; //hold on to the search tag
    var form = document.getElementById('students'); // get the student form
    if(isNumber && search){ // if numeric and is something
        $('#students').empty(); // clear studentform
        $('#students').append(temp); // add search tag
        $.ajax ({
            url : 'https://tvil.hig.no/json_services/getUserDetails.php',
            data : {
                'uid': search
            },
            crossDomain : true,
            type : 'POST',
            dataType : 'json',
            success : function (data) {
                var array = new Array(); // creates a temp array
                for (e in data) {
                    array.push(data[e]); // puts userinfo in an array
                }
                if(array.length > 2) {  // if the array is longer than 2 then its success
                    var list = document.createElement('li'); // create a list element
                    list.name = search;    // set list name as studnr        
                    list.setAttribute('class', 'studentlist'); // set class to list(css)
                    if(ingrp == true) { // if the user are in a grp add posibility to add student
                        var img = document.createElement('img'); // create image with attributs
                        img.setAttribute('onclick', 'add_member(this);');  // create onclick event to image 
                        img.src = "LnF/check_24x20.png";    // set icon
                        img.height = "15";  // set height
                        list.appendChild(img); // append to list
                    }
                    list.innerHTML += '<span>' + array[1] + ', ' + array[0] + '</span>'; // add name to list
                    form.appendChild(list); // append to form
                    
                } else {
                    $('#students').append('<h3>Ingen student med studentnummer '+search+' funnet!</h3>');                           
                }                             // fant ingen student
            }
        });        
    } else if(!isNumber && search) {  
        $('#students').empty(); // clear the student form
        $('#students').append(temp); // add search tag
        $.ajax ({
            url : 'https://tvil.hig.no/json_services/searchUser.php',
            data : {
                'search': search
            },
            crossDomain : true,
            type : 'POST',
            dataType : 'json',
            success : function (data) {                
                if (data.error!=null) { // if didnt find student
                    $('#students').append('<h3>Ingen studenter med navn '+search+' funnet!</h3>');
                } else {
                    for (i in data) { // loops trough the students found
                        var array = new Array(); // creates a temp array
                        for (e in data[i]) { // loop trough the info
                            array.push(data[i][e]); // puts userinfo in an array
                        }
                        var list = document.createElement('li'); // create a list element
                        list.name = array[0];    // set list name        
                        list.setAttribute('class', 'studentlist'); // set class to list(css)
                        if(ingrp == true) {
                            var img = document.createElement('img'); // create image with attributs
                            img.setAttribute('onclick', 'add_member(this);');  // create onclick event to image 
                            img.src = "LnF/check_24x20.png";
                            img.height = "15";
                            list.appendChild(img);
                        }
                        list.innerHTML += '<span>' + array[2] + ', ' + array[1] + '</span>'; // add name to list
                        form.appendChild(list); // append to student form
                    }
                    
                }              
            }
        });
    } else {
        alert("Du kan ikke søke på ingenting ;-)");
    }        // if search  is empty
}

/*
 * This function will find and return a student from the arra
 */
function getStudent(uid) {    
    for (stud in allStudents){ // loops trough the students
        if(uid == allStudents[stud].get_uId()){ // if match then return
            return allStudent[stud];
        }
    }
    return null; // no match return null
}